<template><!--待发布-->
	<div class="">
		<div class="myarticles_padding" v-show="hasSelectedItems">
			<div class="myarticles_top">
				<div class="myarticles_top_left">已选择{{ selectedCount }}项</div>
				<div class="myarticles_top_right">
					<button class="top_right_list" @click="pushSelected">批量发布</button>
					<button class="top_right_list" @click="showChangeClass = !showChangeClass">转移分类</button>
					
					<button class="top_right_list" @click="deleteSelected">批量删除</button>
					<div class="top_right_list" @click="cancelSelection">取消选择</div>
				</div>
			</div>
		</div>

		<!-- 转移分类 -->
		<div class="batchRelease" v-show="showChangeClass">
			<div class="Preview_content">
				<div class="Preview_content_title">
					<div class="content_title_left"><span></span>转移分类</div>
					<div class="content_title_right" @click="showChangeClass = !showChangeClass"><i
							class="el-icon-close"></i></div>
				</div>
				<div class="Edit_content">

					<div class="Edit_content_list">
						<div class="content_list_dd">目标分类</div>
						<div class="content_list_dt">
							<el-select v-model="change_class" placeholder="请选择要将文章转移到哪个分类里">
								<el-option v-for="item in class_types" :key="item.id" :label="item.name"
									:value="item.id">
								</el-option>
							</el-select>
						</div>
					</div>

				
					
				</div>
				<div class="Edit_btn">
					<button class="back" @click="showChangeClass = !showChangeClass">返回</button>
					<button class="save" @click="setChangeClass">开始转移</button>
				</div>
			</div>
		</div>

		<!-- 批量发布 -->
		<div class="batchRelease" v-show="showbatchRelease">
			<div class="Preview_content">
				<div class="Preview_content_title">
					<div class="content_title_left"><span></span>批量发布</div>
					<div class="content_title_right" @click="showbatchRelease = !showbatchRelease"><i
							class="el-icon-close"></i></div>
				</div>
				<div class="Edit_content">
					<div class="Edit_content_list">
						<div class="content_list_dd">站点</div>
						<div class="content_list_dt">
							<el-select v-model="site" placeholder="请选择网站" @change="changeSite">
								<el-option v-for="item in sites" :key="item.id" :label="item.name" :value="item.id">
								</el-option>
							</el-select>
							<a href="/member/#/writing/siteManagement" target="_blank" class="dt_list_icon"><img src="@a/img/sv4.svg" />
							</a>
						</div>
					</div>
					<div class="Edit_content_list">
						<div class="content_list_dd">栏目</div>
						<div class="content_list_dt">
							<el-select v-model="site_class" placeholder="请选择网站栏目">
								<el-option v-for="item in site_classes" :key="item.id" :label="item.name"
									:value="item.id">
								</el-option>
							</el-select>
						</div>
					</div>
					<div class="Edit_content_list paddleft martop">
						<div class="content_list_dd">图片</div>
						<div class="content_list_dt noflxe">
							<div class="radio">
								<el-checkbox v-model="isChecked">插入图片</el-checkbox>
							</div>
							<el-select v-model="img_class" placeholder="请选择图片分类" v-show="isChecked">
								<el-option v-for="item in img_classes" :key="item.id" :disabled="item.count==0?true:false" :label="item.name_all"
									:value="item.id">
								</el-option>
							</el-select>
							<a href="/member/#/writing/pictureManagement" target="_blank" v-show="isChecked" class="dt_list_icon dt_list_icon2"><img src="@a/img/sv4.svg" /></a>
							<div style="padding-top: 10px;"  v-show="isChecked">
								<span style="font-size: 13px; color:#606266; padding-left:10px; margin-bottom: 5px; display: block;">图片在文章中的位置</span>
								<el-select v-model="img_line" placeholder="图片插入位置">
									<el-option v-for="item in img_line_inc" :label="item.name"
										:value="item.value">
									</el-option>
								</el-select>
							</div>
						</div>
					</div>
					
					<div class="Edit_content_list martop">
						<div class="content_list_dd">
							SEO链轮
							<el-tooltip class="item" effect="dark" content="点击查看使用方法" placement="top-start">
								<el-button><a href="https://www.ai-dog.net/help/ruanwen/13.html" target="_blank"><img src="@a/img/sv12.svg" /></a></el-button>
							</el-tooltip>
						</div>
						<div class="content_list_dt">
							<el-checkbox v-model="is_relation" style="margin-bottom: 5px;">开启文章关联</el-checkbox>
							<div class="list_dt_slider" v-show="is_relation" style="align-items: center; font-size: 13px; color: #474b5a; justify-content: space-between; align-items: center; padding-right: 10px; padding-bottom:10px;">
								<div style="font-size: 13px; color: #474b5a; margin-top: 10px; ">相关文章条数：在{{relation_num}}之间</div>
								
								<div style="width: calc(100% - 105px);">
									<el-slider
									v-model="relation_num"
									range
									show-stops
									show-tooltip
									:min="1"
									:max="10">
									</el-slider>
								</div>
							</div>
							<span style="font-size: 13px; color: #474b5a;" v-show="is_relation">自定义相关文章标题</span>
							<el-input v-model="relation_title" v-show="is_relation" placeholder=""></el-input>
							<div style="font-size: 13px; color: #999; margin-top: 10px;" v-show="is_relation">标题中必须包含[keywords]关键词，具体见<a href="https://www.ai-dog.net/help/ruanwen/13.html" target="_blank">“帮助中心”</a></div>
						</div>
					</div>					
					
				</div>
				<div class="Edit_btn">
					<button class="back" @click="showbatchRelease = !showbatchRelease">返回</button>
					<button class="save" @click="toPush">提交保存</button>
				</div>
			</div>
		</div>
		<div class="Published_process" v-if="published_process">
			<div class="Preview_content"><el-progress type="circle" width="180" stroke-width="10" :percentage="published_percent"></el-progress></div>
		</div>

		<!-- 发布成功 -->
		<div class="PublishedSuccessfully" v-if="PublishedSuccessfully">
			<div class="Preview_content">
				<div class="Preview_content_title">
					<div class="content_title_left"><span></span>发布成功</div>
					<div class="content_title_right" @click="PublishedSuccessfully = !PublishedSuccessfully"><i
							class="el-icon-close"></i></div>
				</div>
				<div class="PublishedSuccessfully_content">
					发布完成，总计发布{{push_result.total}}条信息，发布成功{{push_result.success}}条，发布失败{{push_result.fail}}条，具体可见发布
					<router-link to="/writing/releaselog" class="PublishedSuccessfully_content_btn">日志</router-link>
				</div>
				<!--            <div class="Edit_btn">-->
				<!--                <button class="save" @click="ClickProgress">刷新页面</button>-->
				<!--            </div>-->
			</div>
		</div>


		<div class="myarticles_content tobereleased">
			<div class="myarticles_content_title">
				<div class="content_title_list">
					<label>
						<input type="checkbox" v-model="selectAll">
						序号
					</label>
				</div>
				<div class="content_title_list">分类</div>
				<div class="content_title_list">标题</div>
				<div class="content_title_list">审核状态</div>
				<div class="content_title_list">创作时间</div>
				<div class="content_title_list">操作</div>
			</div>
			<div class="myarticles_content_tab">
				<div class="content_tab_list" :class="{ on: info.checked }" v-for="(info, index) in infos.data"
					:key="index">
					<div class="tab_list_li">
						<label>
							<input type="checkbox" v-model="info.checked">
							{{ info.id }}
						</label>
					</div>
					<div class="tab_list_li"><a :href="'/index/ArticleList/index.html?member_id='+$store.getters.memberInfo.id+'&class_id='+info.article_class_id" target="_blank">{{ info.articleClass.name }}</a></div>
					<a class="tab_list_li" :href="'/index/ArticleList/show.html?id='+info.id" target="_blank"><span class="list_li_btn">{{ info.name }}</span></a>
					<div class="tab_list_li ApprovalStatus on"><span></span>已审核</div>
					<div class="tab_list_li">{{ info.update_time }}</div>
					<div class="tab_list_li operate">
						<div class="list_li_btn" @click="preview(info.id)"><img src="@a/img/sv9.svg" />预览</div>
						<div class="list_li_btn" @click="toEditor(info.id)"><img src="@a/img/sv5.svg" />编辑</div>
					</div>
				</div>
				<div class="not_data not_data2" v-show="infos.data.length === 0">
					<div class="not_data_icon"><img src="@a/img/bg26.jpg" /></div>
					<div class="not_data_title">暂无创作任务，点击批量<router-link to="/writing/titleGeneration"
							class="data_title_btn">创作标题</router-link>
					</div>
				</div>
			</div>
		</div>




		<!-- 预览 -->
		<div class="Preview" v-show="showPreview">
			<div class="Preview_content">
				<div class="Preview_content_title">
					<div class="content_title_left"><span></span>预览</div>
					<div class="content_title_right" @click="showPreview = !showPreview"><i class="el-icon-close"></i>
					</div>
				</div>
				<div class="Preview_content_txt">
					<div class="content_txt_title"> {{editorData.name }}</div>
					
					<div ref="htmlContent" v-html="editorData.content"></div>
					<div class="content_txt_title2" v-if="editorData.keywords"> 关键词：{{editorData.keywords }}</div>
				</div>
				<div class="Preview_content_btn">
					<div class="content_btn_list close" @click="showPreview = !showPreview">关闭</div>
					<div class="content_btn_list copy" @click="copyHtml">复制</div>
				</div>
			</div>
		</div>


		<!-- 编辑 -->
		<div class="Preview Edit" v-show="showEdit">
			<div class="Preview_content">
				<div class="Preview_content_title">
					<div class="content_title_left"><span></span>编辑</div>
					<div class="content_title_right" @click="showEdit = !showEdit"><i class="el-icon-close"></i></div>
				</div>
				<div class="Edit_content">
					<div class="Edit_content_list">
						<div class="content_list_dd">标题</div>
						<div class="content_list_dt">
							<el-input placeholder="请输入内容" v-model="editorData.name" clearable>
							</el-input>
						</div>
					</div>
					<div class="Edit_content_list">
						<div class="content_list_dd">文章分类</div>
						<div class="content_list_dt">
							<el-select v-model="editorData.article_class_id" placeholder="默认分类">
								<el-option v-for="item in class_types" :key="item.id" :label="item.name"
									:value="item.id">
								</el-option>
							</el-select>
						</div>
					</div>
					<div class="Edit_content_list">
						<div class="content_list_dd">关键词</div>
						<div class="content_list_dt">
							<el-input placeholder="请输入内容" v-model="editorData.keywords" clearable>
							</el-input>
						</div>
					</div>					
					<div class="Edit_content_list Edit_content_txt">
						<div class="content_list_dd">内容</div>
						<div class="content_list_dt">
							<Editor api-key="uzmcaumu2y7g9r2etb3dbozjg2tljvaktxze4e3hptkrjul0" id="tinymceId"
								v-model="editorData.content" :init="initEditor"></Editor>
						</div>
					</div>
				</div>
				<div class="Edit_btn">
					<button @click="editorSave">保存</button>
				</div>
			</div>
		</div>


		<!-- 发布进度条 -->
		<div class="ProgressBar" v-if="show">
			<div class="ProgressBar_icon">
				<el-progress :text-inside="true" :stroke-width="60" :percentage="progress" :color="colors"
					status="success"></el-progress>
			</div>
		</div>


		<div class="page">
			<el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
				:current-page="infos.current_page" :page-sizes="infos.per_pages" :page-size="infos.per_page"
				layout="total, sizes, prev, pager, next, jumper" :total="infos.total">
			</el-pagination>
		</div>

	</div>
</template>

<script>
	import {
		Message,
		MessageBox
	} from 'element-ui';
	import axios from 'axios';
	import Editor from '@tinymce/tinymce-vue' //编辑器引入
	import {
		Loading
	} from 'element-ui';

	let loadingInstance1 = null;

	export default {
		name: "toBereleased",
		props: {
			infos: {
				type: Object,
				default: {
					data: [],
					per_page: 20,
					current_page: 1,
					last_page: 1,
					total: 0
				},
			},
		},
		data() {
			return {
				relation_num: [4, 6],
				isChecked: false,
				is_relation: false,
				input: "",
				PublishedSuccessfully: false,
				showbatchRelease: false,
				showChangeClass:false,
				initEditor: {
					selector: '#tinymceId',
					language: "zh_CN",
					height: 430,
					menubar: false,
					toolbar: 'undo redo | formatselect | bold italic backcolor | \
            alignleft aligncenter alignright alignjustify | \
            bullist numlist outdent indent | removeformat '
				},
				class_types: [],
				change_class:"",
				editorData: {
				 id: 0,
					name: '',
					content: '',
					article_class_id: 0
				},
				push_result: {
					total: 0,
					success: 0,
					fail: 0
				},
				showPreview: false,
				showEdit: false,
				content: '',
				per_pages: [20, 50, 100 ,200],
				site: '',
				sites: [],
				site_class: '',
				site_classes: [],
				img_class: null,
				img_classes: [],
				img_line: 1,
				img_line_inc: [
					{ name: "随机", value: 0},
					{ name: "第一段前", value: 1},
					{ name: "第二段前", value: 2},
					{ name: "第三段前", value: 3},
					{ name: "第四段前", value: 4},
					{ name: "第五段前", value: 5},
					{ name: "第六段前", value: 6},
					{ name: "文章结束", value: 100},
				],
				relation_title:"更多和<b>”[keywords]“</b>相关的文章",
				progress: 0,
				colors: [{
					color: '#3662eb'
				}, ],
				timer: null,
				show: false,
				published_process:false,//是否展示发布中的进度条
				published_percent:0,//进度条百分比
				pushIds:[],//勾选要发布的文章
			};
		},
		components: {
			Editor
		},

		computed: {
			//全选
			selectAll: {
				get() {
					return this.infos.data.every(info => info.checked)
				},
				set(value) {
					console.log(value)
					this.infos.data.forEach(info => {
						info.checked = value
					})
				},
			},
			selectedCount() {
				return this.infos.data.filter(info => info.checked).length
			},
			allCount() {
				return this.infos.data.filter(info => info).length
			},
			hasSelectedItems() {
				return this.infos.data.filter(info => info.checked).length > 0;
			},
		},
		created() {
			this.getSites()
			this.getImgClass()
			this.getArticleClass()
		},
		methods: {
			openNewWindowsiteManagement() {
				window.open('../#/writing/siteManagement', '_blank');
			},
			openNewWindowpictureManagement() {
				window.open('../#/writing/pictureManagement', '_blank');
			},
			//复制
			copyHtml() {
				const htmlElement = this.$refs.htmlContent
				const range = document.createRange()
				range.selectNode(htmlElement)
				window.getSelection().removeAllRanges()
				window.getSelection().addRange(range)
				document.execCommand('copy')
				window.getSelection().removeAllRanges()
				this.$message.success('已复制到剪贴板')
			},
			//设置文章分类转移
			setChangeClass() {
				let ids = []
				for (let i = this.infos.data.length - 1; i >= 0; i--) {
					if (this.infos.data[i].checked) {
						ids.push(this.infos.data[i].id)
					}
				}
				this.axios.post('/api/article/changeClass', {
					ids: ids,
					article_class_id: this.change_class,
				}).then(res => {
					if (res.code === 1) {
						this.$message.success('转移成功');
						this.$emit('refresh');
						this.showChangeClass=false;
					}
				})
			},			
			//发送文章
			toPush() {
				//loadingInstance1 = Loading.service({});
				let ids = []
				for (let i = this.infos.data.length - 1; i >= 0; i--) {
					if (this.infos.data[i].checked) {
						ids.push(this.infos.data[i].id)
					}
				}
				this.published_process=true;//开启进度条
				this.pushIds=ids;
				this.published_percent=0;//初始化发送进度
				this.push_result.total=ids.length;//发送量
				this.push_result.success=0;//初始化发送成功数量
				this.push_result.fail=0;//初始化发送失败数量
				this.sendPush(0);
			},
			sendPush(key) {
				let that = this;
				that.axios.post('/api/article/push2', {
					id: this.pushIds[key],
					site_id: that.site,
					site_class_id: that.site_class,
					is_insert_img: that.isChecked,
					img_class_id: that.img_class,
					img_line: that.img_line,
					is_relation: that.is_relation,
					relation_num: that.relation_num,
					relation_title: that.relation_title,
				}).then(res => {
					//验证通过
					if (res.code === 1) {
						if (res.result === 1) {
							that.push_result.success++;
						}else{
							that.push_result.fail++;
						}						
						//设置进度条
						let percent=(key+1)/that.pushIds.length;
						percent=Math.ceil(percent*100);
						that.published_percent=percent;
						//
						if(key<that.pushIds.length-1){
							that.sendPush(key+1);
						}else{
							this.published_process=false;//关闭进度条
							that.PublishedSuccessfully = true;//开启发送结果面板
							that.$emit('refresh');
							that.showbatchRelease = false;
						}	
					}else{
					//验证不通过
						this.published_process=false;//关闭进度条
					}
					

				})
			},			
			changeSite(val) {
				loadingInstance1 = Loading.service({});
				this.getSiteClasses()
			},
			getSites() {
				let that = this;
				this.axios.get('/api/site/list').then(res => {
					res.result.data.forEach(item => {
						item.isActive = false
					})
					that.sites = res.result.data
				})
			},
			getSiteClasses() {
				let that = this;
				this.axios.post('/api/site/getClassesById', {
					id: this.site
				}).then(res => {
					res.result.forEach(item => {
						item.isActive = false
					})
					console.log(res)
					that.site_classes = res.result
					this.$nextTick(() => { // 以服务的方式调用的 Loading 需要异步关闭
						loadingInstance1.close();
					});
				})
			},
			getImgClass() {
				let that = this;
				this.axios.get('/api/imgClass/list').then(res => {
					res.result.forEach(item => {
						item.isActive = false
					})
					that.img_classes = res.result
				})
			},
			preview(id) {
				let that = this;
				let callback = () => {
					that.showPreview = !that.showPreview
				}
				that.getEditorData(id, callback)
			},

			getArticleClass() {
				let that = this;
				this.axios.get('/api/articleClass/list').then(res => {
					res.result.forEach(item => {
						item.isActive = false
					})
					that.class_types = res.result
				})
			},
			toEditor(id) {
				let that = this;
				let callback = () => {
					that.showEdit = true
				}
				that.getArticleClass();
				that.getEditorData(id, callback)
			},
			getEditorData(id, callback) {
				let that = this;
				that.axios.get('/api/article/getEditor', {
					params: {
						id: id
					}
				}).then(res => {
					if (res.code == 1) {
						that.editorData = res.result
						callback()
					}
				})
			},
			editorSave() {
				let that = this;
				that.axios.post('/api/article/editor', that.editorData).then(res => {
					if (res.code == 1) {
						that.$message.success('保存成功');
						that.$emit("refresh")
						that.showEdit = false
					}
				})
			},
			getContent(id, callback) {
				let that = this;
				that.axios.get('/api/article/getContent', {
					params: {
						id: id
					}
				}).then(res => {
					if (res.code == 1) {
						that.content = res.result.content
						callback()
					}
				})
			},
			//分页
			handleSizeChange(val) {
				this.$emit('changeSize', val)
			},
			handleCurrentChange(val) {
				this.$emit('changePage', val)
			},
			//取消选择
			cancelSelection() {
				this.selectAll = false;
			},
			//批量删除
			deleteSelected() {
				let that = this;
				let ids = []
				for (let i = this.infos.data.length - 1; i >= 0; i--) {
					if (this.infos.data[i].checked) {
						ids.push(this.infos.data[i].id)
					}
				}
				MessageBox.confirm(`确定删除文章吗？`, '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(() => {
					that.axios.post('/api/article/delete', {
						ids: ids
					}).then(
						(res) => {
							if (res.code === 1) {
								that.$message({
									type: 'success',
									message: '删除成功!'
								});
								that.$emit('refresh')
							}

						}
					)
					this.selectAll = false;
				}).catch(() => {
					this.$message({
						type: 'info',
						message: '已取消删除'
					});
					// 用户点击取消或者弹窗关闭时不做任何操作
				});
			},
			//批量发布
			pushSelected() {
				let that = this;
				let ids = []
				for (let i = this.infos.data.length - 1; i >= 0; i--) {
					if (this.infos.data[i].checked) {
						ids.push(this.infos.data[i].id)
					}
				}
				MessageBox.confirm(`确定要批量发布文章吗？【Ps：系统每天自动随机发布10条】`, '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(() => {
					that.axios.post('/api/article/setPush', {
						ids: ids
					}).then(
						(res) => {
							if (res.code === 1) {
								that.$message({
									type: 'success',
									message: '发布成功!'
								});
								that.$emit('refresh')
							}

						}
					)
					this.selectAll = false;
				}).catch(() => {
					this.$message({
						type: 'info',
						message: '已取消'
					});
					// 用户点击取消或者弹窗关闭时不做任何操作
				});
			},			
			//进度
			ClickProgress() {
				this.show = !this.show;
				// 直接设置进度为100%
				axios.interceptors.request.use(config => {
					this.progress = 0;
					return config;
				});
				axios.interceptors.response.use(response => {
					this.progress = 100;
					if (response.data && response.data.length > 0) {
						this.data = response.data;
					}
					return response;
				}, error => {
					this.progress = 100;
					console.log(error);
					return Promise.reject(error);
				});
				axios.get('http://api.gpt.jijinweb.com/test.php?s=5')
					.catch(error => {
						console.log(error);
					});

				this.timer = setInterval(() => {
					if (this.messages.length > 0) {
						const msg = this.messages.shift();
						Notification({
							title: msg.title,
							message: msg.message
						});
					} else {
						clearInterval(this.timer);
					}
				}, 1000);
			}
		},
	}
</script>

<style>
	@import "toBereleased.css";
</style>
